<?php
namespace coreLib\db\MysqlClass;
use coreLib\ErrorClass\Error;

/**
 * mysql数据库操作类
 **/
class Mysql{

	public  $mysqlConn;					//操作对象句柄
	private $host;						//数据库地址
	private $username;					//用户名称
	private $password;					//用户密码
	private $dbname;					//数据库名称
	public  $prefix;					//表前缀
	public  $view_prefix;			    //视图前缀
	private $procedureParams; 			//存储过程参数
	private $mysqlResult;				//数据库返回的结果集
	private $mysqlData;					//执行结果
	public  $sql;						//sql语句
	public  $where;						//条件o
	private $field;						//字段
	private $sort;						//排序
	private $in;						//in类型的条件
	private $isCount;					//是否查询总条数
	private $limit;						//分页
	private $nowActionDbName;      	 	//当前操作的数据库名称
	public  $lastAddId;					//添加成功后ID
	private $paramsValue;				//GET请求的条件参数值
	private $searchKeyword;				//特殊查询关键字
	private $automaticAddParams;		//需要自动构建的新增参数
	private $isAutomaticAddParams;  	//是否自动构建新增参数
	private $automaticUpdateParams;		//需要自动构建的更新参数
	private $isAutomaticUpdateParams;	//需要自动构建的更新参数
	private $automaticDeleteParams;		//需要自动构建的删除参数
	private $isAutomaticDeleteParams;	//需要自动构建的删除参数
	private $isPhysicallyDelete;  		//是否满足物理删除条件
	
	/*
	 * 构造方法
	 * @params {$setting} 数据库配置信息
	 * @return 没有返回值
	 */
	function __construct($setting){
 
		$this->host     	   = $setting['host'];
		$this->username 	   = $setting['username'];
		$this->password 	   = $setting['password'];
		$this->dbname 		   = $setting['dbname'];
		// $this->prefix		   = $setting['prefix'];
		// $this->view_prefix	   = $setting['view_prefix'];
		$this->nowActionDbName = $setting['dbname'];
		$this->searchKeyword   = array(
			"sort_order",
			"keywords",
			"like",
			"limit",
			"skip",
			"in",
			"or",
			"between",
			"count",
			"intersection",
			"no",
			"distinct"
		);
		
		//创建mysql数据库连接
		$conn = @new \mysqli($this->host,$this->username,$this->password,$this->dbname);
		
		if(mysqli_connect_error()){
	
			if(!$GLOBALS["settings"]["noDatabaseUse"]){
			   Error::Result("DATABASE_ERROR","Mysql_Error:".mysqli_connect_error());
			}
			
		}else{

			//设置查询编码
			$conn->query("SET NAMES UTF8");

			//数据库连接对象
			$this->mysqlConn = $conn;
		}

	}

	/*自动构建删除字段*/
	function automaticDelete($deleteParams){

		if(count($deleteParams)){

			$this->isAutomaticDeleteParams = true;

			$this->automaticDeleteParams   = $deleteParams;

			if($deleteParams['isPhysicallyDelete'] != NULL && $deleteParams['isPhysicallyDelete'] == 1){

				if($GLOBALS["settings"]["isPhysicallyDelete"]){

					$this->isPhysicallyDelete = true;


				}

			}

			unset($this->automaticDeleteParams['isPhysicallyDelete']);
			
		}

		return $this;

	}

	/*数据库删除操作*/
	function delete($table,$where=[],$data=[]){
		
		$tableName = $table; //$isPrefix ? $this->prefix."_".$table : $table;

		$this->sql = "update ".$tableName;

		$deleteParams = [];

		

		//是否自动构建更新参数
		if($this->isAutomaticDeleteParams){

			$deleteParams = $this->automaticDeleteParams;

			$deleteWhere  = explode(",",$deleteParams['delete_where']);

			unset($deleteParams['delete_where']);

			$whereArr = [];

			foreach($deleteParams as $k=>$v){

				for($i=0;$i<count($deleteWhere);$i++){

					if($k == $deleteWhere[$i]){

						$whereArr[$k] = $v;

						unset($deleteParams[$k]);

					}
					
				}

			}

			$where = $whereArr;
			$data  = $deleteParams;

		}

		

		$whereKey   = " where ";
		foreach($where as $k=>$v){
			$whereKey.= $k."='".$v."' and ";
		}

		$whereKey = rtrim($whereKey," and ");

		//判断是否物理删除
		if($this->isPhysicallyDelete){

			$this->sql = "delete from ".$table;
			
			$deleteKey = rtrim($deleteKey,",");

			$this->sql .= $deleteKey.$whereKey;

			if($GLOBALS['settings']['debug']){
				$GLOBALS['settings']['interfaceInfo'][] = "SQL语句: ".$this->sql;
			}

			//执行SQL
			return $this->execSql();

		}



		$deleteKey   = " set ";
		foreach($data as $k=>$v){
			$deleteKey.= $k."='".$v."',";
		}

		$deleteKey = rtrim($deleteKey,",");

		
		$this->sql .= $deleteKey.$whereKey;

		if($GLOBALS['settings']['debug']){
			$GLOBALS['settings']['interfaceInfo'][] = "SQL语句: ".$this->sql;
		}

		//执行SQL
		return $this->execSql();
		
	}

	/*自动构建更新字段*/
	function automaticUpdate($updateParams){

		if(count($updateParams)){

			$this->isAutomaticUpdateParams = true;

			$this->automaticUpdateParams   = $updateParams;

		}

		return $this;

	}

	/*关闭事物自动提交*/
	function falseAutoCommit(){
		$this->mysqlConn->autocommit(false);
	}

	/*开启事物自动提交*/
	function trueAutoCommit(){
		$this->mysqlConn->autocommit(true);
	}

	/*回滚事物提交*/
	function rollBackCommint(){
		$this->mysqlConn->rollback();
	}

	/*事物提交*/
	function actionCommint(){
		$this->mysqlConn->commit();
	}

	/*数据库更新操作*/
	function update($table,$where=[],$data=[]){

		$tableName = $table; //$isPrefix ? $this->prefix."_".$table : $table;

		$this->sql = "update ".$tableName;

		$updateParams = [];

		//是否自动构建更新参数,查询该表结构
		if($this->isAutomaticUpdateParams){

			$updateParams = $this->automaticUpdateParams;

			$updateWhere  = explode(",",$updateParams['update_where']);

			unset($updateParams['update_where']);

			$whereArr = [];

			foreach($updateParams as $k=>$v){

				for($i=0;$i<count($updateWhere);$i++){

					if($k == $updateWhere[$i]){

						$whereArr[$k] = $v;

						unset($updateParams[$k]);

					}
					
				}

			}

			$where = $whereArr;
			$data  = $updateParams;

		}

		$whereKey   = " where ";
		foreach($where as $k=>$v){
			$whereKey.= $k."='".$v."' and ";
		}

		$whereKey = rtrim($whereKey," and ");

		$updateKey   = " set ";
		foreach($data as $k=>$v){
			$updateKey.= $k."='".$v."',";
		}

		$updateKey = rtrim($updateKey,",");

		$this->sql .= $updateKey.$whereKey;
	
		if($GLOBALS['settings']['debug']){
			$GLOBALS['settings']['interfaceInfo'][] = "SQL语句: ".$this->sql;
		}

		//执行SQL
		return $this->execSql();
	}

	/*自动构建写入字段*/
	function automaticAdd($addParams){

		if(count($addParams)){

			$this->isAutomaticAddParams = true;

			$this->automaticAddParams = $addParams;

		}

		return $this;

	}

	/*开启事物的数据库写入操作*/
	function insertTransaction($table,$data=[]){

		$tableName = $table; //$isPrefix ? $this->prefix."_".$table : $table;

		$this->sql = "insert into ".$tableName;

		$addParams = [];
		
		//是否自动构建添加参数,查询该表结构
		if($this->isAutomaticAddParams){

			$addParams = $this->automaticAddParams;

		}else{

			$addParams = $data;

		}

		//创建写入SQL语句的字段项
		$insertKey   = "(";
		$insertValue = "(";
		foreach($addParams as $k=>$v){
			$insertKey   = $insertKey."".$k.",";
			$insertValue = $insertValue."'".$v."',";
		}

		$insertKey = rtrim($insertKey,",").")";
		$insertValue = rtrim($insertValue,",").")";

		$this->sql = $this->sql.$insertKey." values".$insertValue;

		//执行查询
		$this->mysqlResult = $this->mysqlConn->query($this->sql);

		if(!$this->mysqlResult){
			return 0;
		}
		
		$this->lastAddId = mysqli_insert_id($this->mysqlConn); 

		if($GLOBALS['settings']['debug']){
			$GLOBALS['settings']['interfaceInfo'][] = "SQL语句: ".$this->sql;
		}

		//执行SQL
		return $this->lastAddId;
	}

	/*数据库写入操作*/
	function insert($table,$data=[]){

		$tableName = $table; //$isPrefix ? $this->prefix."_".$table : $table;

		$this->sql = "insert into ".$tableName;

		$addParams = [];
		
		//是否自动构建添加参数,查询该表结构
		if($this->isAutomaticAddParams){

			$addParams = $this->automaticAddParams;

		}else{

			$addParams = $data;

		}

		//创建写入SQL语句的字段项
		$insertKey   = "(";
		$insertValue = "(";
		foreach($addParams as $k=>$v){
			$insertKey   = $insertKey."".$k.",";
			$insertValue = $insertValue."'".$v."',";
		}

		$insertKey = rtrim($insertKey,",").")";
		$insertValue = rtrim($insertValue,",").")";

		$this->sql = $this->sql.$insertKey." values".$insertValue;

		//执行查询
		$this->mysqlResult = $this->mysqlConn->query($this->sql);

		if(@$isDatabaseTransaction){
			if(!$this->mysqlResult){
				return 0;
			}
		}else{
			if(!$this->mysqlResult){
				Error::Result("REQUEST_ERROR",mysqli_error($this->mysqlConn));
			}
		}

		$this->lastAddId = mysqli_insert_id($this->mysqlConn); 

		if($GLOBALS['settings']['debug']){
			$GLOBALS['settings']['interfaceInfo'][] = "SQL语句: ".$this->sql;
		}

		//执行SQL
		return $this->lastAddId;
	}	


	/*
     * 切换数据库操作
     * @params {$dbName} 切换的数据库名称
	 * @return 返回当前操作对象，用于链式操作
	 */
	function useDB($dbName){

		$this->mysqlConn->query("use ".$dbName);

		$this->nowActionDbName = $dbName;

		return $this;
	}

	/*
     * 字段过滤
     * @params {$field} 需要显示的字段数组
	 * @return 返回当前操作对象，用于链式操作
	 */
	function field( $field ){

		if( $field && $field['fields'] != NULL){

			if( is_array( $field['fields'] ) ){
	        	$newField = "";
	        	if(count($field['fields'])){
	            	//组装字段
	            	foreach($field['fields'] as $k=>$v){
	                	if(empty($v)){
	                    	$newField .= $k.",";
	                	}else{
	                    	$newField .= $k." as ".$v.",";
	               		}
	            	}
	            	$this->field = rtrim($newField,",");
	       		 }
	    	}else{
	        		$this->field=$field['fields'];
	    	}
		}
		return $this;
	}

	/*
	 * 请求参数分析
	 * @params {$params} 请求参数数组
	 * @return 返回当前操作对象，用于链式操作
	 */
	function params($params){

		$whereStr = "";
		$sortStr  = "";
		$limitStr = "";
		$inStr    = "";

		if(count($params)){

			$this->paramsValue = $params;

			foreach($params as $k=>$v){

				if(!in_array($k,$this->searchKeyword)){
					$where_arr=explode("-", $v);
					$whereStr  .= $k." = '".$v."' and ";
				}

				//模糊关键字查询
    			if($k == "keywords"){
					 $whereArr = explode("-", $v);
						 
					 if($whereArr[2] == NULL){
						$whereStr .=$whereArr[0]." like '%".$whereArr[1]."%'"." and ";
					 }else{
						
						if($whereArr[2] == 'end'){

							$whereStr .= $whereArr[0]." like '%".$whereArr[1]."'"." and ";

						}else if($whereArr[2] == 'start'){
							$whereStr .= $whereArr[0]." like '".$whereArr[1]."%'"." and ";
						}
					 }

    			}
				
				//排序操作
    			if($k == "sort_order"){
    
    			   //获取左右排序key与值
				   $sortArr = explode("-", $v);
				   if(count($sortArr) == 3){
					$sortStr .= $sortArr[0]." ".$sortArr[2].",".$sortArr[1]." ".$sortArr[2];
				   }else{
					$sortStr .= $sortArr[0]." ".$sortArr[1];
				   }
    			}
				
				//包含操作
    			if($k == "in"){

    			   //获取左右排序key与值
				   $inArr = explode("-", $v);

				   //判断字符串中是否包含#号，如果包含替换回/	
				   $inArr[1] = str_replace('@','/',$inArr[1]);	

				   $inValueArr = explode(",",$inArr[1]);

				   $inValue = "";
				   for($i=0;$i<count($inValueArr);$i++){
					   $inValue.= "'".$inValueArr[$i]."',";
				   }
				
				   $inValue = rtrim($inValue,",");
				 
    			   $inStr .= $inArr[0]." in($inValue) and ";
				
				}

				//去重
				if($k == 'distinct'){

					//获取左右排序key与值
					$inStr .= " group by ".$v;

				}

				//或查询
				if($k == "or"){

					//判断是否有多少条件
					$moreOrArr = explode("|", $v);

					$inStr .= "(";

					for($i=0;$i<count($moreOrArr);$i++){

						$orItem = $moreOrArr[$i];

						//获取左右排序key与值
						$inArr = explode("-", $orItem);
						$orArr = explode(",",$inArr[1]);

						if($orArr[1]){
							$inStr .= "(".$inArr[0]."='".$orArr[0]."' or ".$inArr[0]."='".$orArr[1]."') or ";
						}else{
							$inStr .= "(".$inArr[0]."='".$orArr[0]."') or ";
						}

					}	

					$inStr = rtrim($inStr," or ");
				
					$inStr .= ") and ";

				}

				//交集查询
				if($k == 'no'){

					//获取左右排序key与值
					$noArr = explode("-", $v);
					$inStr .= " (".$noArr[0]."!=".$noArr[1].")";

				}

				//交集查询
				if($k == 'intersection'){

					$intersectionArr = explode("|", $v);

					$inStr .= "not (";

					$intersectionArr_l = explode("-", $intersectionArr[0]);
					$intersectionArr_r = explode("-", $intersectionArr[1]);

					$inStr .= "(" .$intersectionArr_l[0]."<".$intersectionArr_l[1].") or ";
					$inStr .= "(" .$intersectionArr_r[0].">".$intersectionArr_r[1].")";

					$inStr .= ") and ";

				}

				//范围查询
				if($k == 'between'){


					$betweenArr = explode("|", $v);

					if(count($betweenArr)<=1){


						$betweenArr = explode("-", $v);
					
						if(count($betweenArr) == 3){
							
							$inStr .= "(".$betweenArr[1]." > ".$betweenArr[0]." and ".$betweenArr[1]." < ".$betweenArr[2].")";
	
						}else{

							$inStr .= "(";
	
							if(is_numeric($betweenArr[0])){
	
								$inStr .= $betweenArr[1]." > ".$betweenArr[0];
	
							}
	
	
							if(is_numeric($betweenArr[1])){
	
								$inStr .= $betweenArr[0]." < ".$betweenArr[1];
	
							}

							$inStr .= ")";

							$inStr .= " and ";
						}


					}else{

					
						for($i=0;$i<count($betweenArr);$i++){

							$betweenArr2 = explode("-", $betweenArr[$i]);
							
							if(count($betweenArr2) == 3){

								$inStr .= "(".$betweenArr2[1]." > ".$betweenArr2[0]." and ".$betweenArr2[1]." < ".$betweenArr2[2].") and ";
								
							}else{

								if(is_numeric($betweenArr2[0])){
		
									$inStr .= $betweenArr2[1]." > ".$betweenArr2[0]." and ";
		
								}
		
		
								if(is_numeric($betweenArr2[1])){
		
									$inStr .= $betweenArr2[0]." < ".$betweenArr2[1]." and ";
		
								}
							}

						}

					}
					
					
				}

				//总数查询
				if($k == 'count'){
					$this->isCount = true;
				}
			}

			$arrStr = explode(" and ", $inStr);
            if ($arrStr[count($arrStr)-1] == "") {
                $inStr = rtrim($inStr," and ");
            }

    		$whereStr = rtrim($whereStr," and");
		}

		//分页参数拼接处理
		if(isset($params['skip']) || isset($params['limit'])){
			if(!isset($params['skip']) || !isset($params['limit'])){
				Error::Result("DATABASE_ERROR",$GLOBALS['errorMsg']['paramsFormatError']);
			}
			$limitStr = $params['skip'] . ',' . $params['limit'];
		}else{
			$limitStr = '0,'.$GLOBALS['settings']['pageLimit'];
		}

		$this->where = $whereStr;
		$this->sort  = $sortStr;
		$this->in    = $inStr;
		$this->limit = trim($limitStr,",");

		return $this;
	}

	/*
	 * 排序添加
	 * @params {$sort} 排序字符串
	 * @return 返回当前操作对象，用于链式操作 
	 */
	function sort($sort){

		$this->sort = $sort;
		return $this;
	}

	/*
	 * 分页添加
	 * @params {$skip}  从第几条开始显示
	 * @params {$limit} 显示几条
	 * @return 返回当前操作对象，用于链式操作 
	 */
	function limit($skip,$limit){

		if(empty($skip)){
		   $skip = 0;		
		}

		if(empty($limit)){
		   $limit = $GLOBALS['settings']['pageLimit'];
		}

		$this->limit = $skip.",".$limit;
		return $this;
	}

	/*
	 * 执行sql拼接
	 * @params {$table} 表名称
	 * @return 没有返回值
	 */
	protected function sqlSplite($table,$isCount=false){

		// $tPrefix = $isView ? $this->view_prefix : $this->prefix;

		//判断是否为查询总条数
		if(!$isCount){

			//拼接字段选择
			if($this->field){

				//判断是否存在表前缀
				// if(!empty($tPrefix)){
					// $this->sql = "select ".$this->field." from ".$tPrefix."_".$table;
				// }else{
					$this->sql = "select ".$this->field." from ".$table;
				// }
		
			}else{

				//判断是否存在表前缀
				if(!empty($tPrefix)){
					$this->sql = "select * from ".$tPrefix."_".$table;
				}else{
					$this->sql = "select * from ".$table;
				}
			}

		}else{

			//判断是否存在表前缀
			if(!empty($tPrefix)){
				$this->sql = "select count(*) as num from ".$tPrefix."_".$table;
			}else{
				$this->sql = "select count(*) as num from ".$table;
			}

		}

		//拼接条件
		if($this->where){

			if($this->in){
				$this->sql .= " where ".$this->where." and ".$this->in;
			}else{
				$this->sql .= " where ".$this->where;
			}
			
		}else if($this->in){

			$this->sql .= " where ".$this->in;

		}

		//拼接排序
		if($this->sort){
			$this->sql .= " order by ".$this->sort;
		}

		//拼接分页
		if($this->limit){
			$this->sql .= " limit ".$this->limit;
		}

	}

	/*
     * 查询方法（多数据返回）
     * @params {$table} 表名称
     * @params {$isView} true表为视图，false为普通数据表
	 * @return 查询后的结果，二维数组
	 */
	function select($table,$type="BUSINESS"){

		//执行SQL拼接
		$this->sqlSplite($table,false);

		$originalSql = $this->sql;

		$countRecord = 0;

		if($this->isCount){

			//总记录数
			$countRecord = $this->params($this->paramsValue)->count($table);

		}
		
		$this->sql = $originalSql;

		//执行SQL
		$this->mysqlData = $this->execSql();

		if($GLOBALS['settings']['debug']){
			$GLOBALS['settings']['interfaceInfo'][] = "SQL语句: ".$this->sql;
		}

		return array( "count" => $countRecord , "data" => $this->mysqlData );

		
	}

	/*
     * 查询方法（多数据返回）自定义表名，不使用系统提供的表前缀
     * @params {$table} 表名称
	 * @return 查询后的结果，二维数组
	 */
	function selectTable($table){

		// $this->prefix = "";

		//执行SQL拼接
		$this->sqlSplite($table);

		//执行SQL
		$this->mysqlData = $this->execSql();

		return $this->mysqlData;

	}


	/*
     * 查询总条数
     * @params {$table} 表名称
	 * @return 总条数数量
	 */
	function count($table){

		//判断是否为视图查询，并更改表前缀
		// if($isView){
		// 	$this->prefix = "v";
		// }

		//执行SQL拼接
		$this->sqlSplite($table,true);

		//执行SQL
		$this->mysqlData = $this->execSql();

		
		return $this->mysqlData[0]['num'];

	}


	/*
     * 查询总条数
     * @params {$table} 表名称
	 * @return 总条数数量
	 */
	function countTable($table){

		// $this->prefix = "";

		//执行SQL拼接
		$this->sqlSplite($table,true);

		//执行SQL
		$this->mysqlData = $this->execSql();

		
		return $this->mysqlData[0]['num'];

	}


	/*
     * 查询方法（单条数据返回）
     * @params {$table} 表名称
     * @params {$isView} true表为视图，false为普通数据表
     * @return 查询后的结果，一维数组
	 */
	function find($table){

		//判断是否为视图查询，并更改表前缀
		// if($isView){
		// 	$this->prefix = "v";
		// }

		//执行SQL拼接
		$this->sqlSplite($table);


		//执行SQL
		$this->mysqlData = $this->execSql();


		if($this->mysqlData[0] == NULL){
		   $resutData = array();
		}else{
		   $resutData = $this->mysqlData[0];	
		}

		return $resutData;
	}


	/*
     * 查询方法（单条数据返回）自定义表名，不使用系统提供的表前缀
     * @params {$table} 表名称
	 * @return 查询后的结果，二维数组
	 */
	function findTable($table){

		// $this->prefix = "";

		//执行SQL拼接
		$this->sqlSplite($table);

		//执行SQL
		$this->mysqlData = $this->execSql();
		
		if($this->mysqlData[0] == NULL){
		   $resutData = array();
		}else{
		   $resutData = $this->mysqlData[0];	
		}

		return $resutData;
		
	}

	/*
	 * 事物SQL执行方法
     * @return 返回结果集
	 */
	function queryTransaction($sql){

		//结果保存数组
		$dataArr = array();

		//设置查询编码
		$this->mysqlConn->query("SET NAMES UTF8");

		//执行查询
		$this->mysqlResult = $this->mysqlConn->query($sql);

		if(!$this->mysqlResult){
			return 0;
		}else{
			return 1;
		}
		
	}

	/*
	 * sql执行方法
     * @return 返回结果集
	 */
	function query($sql){

		//结果保存数组
		$dataArr = array();

		//设置查询编码
		$this->mysqlConn->query("SET NAMES UTF8");

		//执行查询
		$this->mysqlResult = $this->mysqlConn->query($sql);

		if(!$this->mysqlResult){
			Error::Result("REQUEST_ERROR",mysqli_error($this->mysqlConn));
		}

		$dataArr = @mysqli_fetch_all($this->mysqlResult,MYSQLI_ASSOC);

		return $dataArr;

	}


	/*
	 * sql执行方法
     * @return 返回结果集
	 */
	function execSql(){

		//结果保存数组
		$dataArr = array();

		//设置查询编码
		$this->mysqlConn->query("SET NAMES UTF8");

		//执行查询
		$this->mysqlResult = $this->mysqlConn->query($this->sql);

		if(!$this->mysqlResult){
			Error::Result("REQUEST_ERROR",mysqli_error($this->mysqlConn));
		}
		
		$dataArr = @mysqli_fetch_all($this->mysqlResult,MYSQLI_ASSOC);


		return $dataArr;
	}
	
	/*
	 * 构造存储过程所需参数
	 * @params {$params} 存储过程参数数组
	 * @params {$actionType} 存储过程的处理类型 C-新增 U-更新 R-查询 D-删除
	 * @params {$wheres} 进行U操作时的条件参数
	 * @return 返回最终拼接好的参数
	 */
	function setProceduerParams($params,$actionType,$wheres=NULL){

		//最终参数结果
		$proParams = "";

		//如果是 写入，查询，删除操作
		if($actionType == 'C' || $actionType == 'R' || $actionType == 'D'){

			//拼装存储过程参数
			for($i=0;$i<count($params);$i++){

				$proParams .= "'".$params[$i]."',";
			}

			$proParams = rtrim($proParams,',');

		//如果是 更新操作	
		}else if($actionType == 'U'){

			//判断是否为关联数组，更新操作要求传递关联数组参数
			if(!is_assoc_array($params) && !is_assoc_array($wheres)){
				Error::Result("BUSINESS_ERROR",$GLOBALS['errorMsg']['noProceduerParamsFormatError']);
			}

			//条件参数处理
			$wheresKeyArr = array();
			$wheresValArr = array();
			foreach($wheres as $k=>$v){

				if(!empty($v)){
					array_push($wheresKeyArr,$k);
					array_push($wheresValArr,$v);
				}
			}

			if(count($wheresKeyArr) != count($wheresValArr)){
				Error::Result("BUSINESS_ERROR",$GLOBALS['errorMsg']['noProceduerParamsCountError']);
			}

			//更新参数处理
			$paramsKeyArr = array();
			$paramsValArr = array();
			foreach($params as $k=>$v){

				if((!empty($v)) || $v == '0'){
					array_push($paramsKeyArr,$k);
					array_push($paramsValArr,$v);
				}

			}



			if(count($paramsKeyArr) != count($paramsValArr)){
				Error::Result("BUSINESS_ERROR",$GLOBALS['errorMsg']['noProceduerParamsCountError']);
			}

			//拼接最终参数结果
			$proParams = "'".implode(",",$wheresKeyArr)."','".implode(",",$wheresValArr)."','".implode(",",$paramsKeyArr)."','".implode(",",$paramsValArr)."'";


		}else {
			Error::Result("BUSINESS_ERROR",$GLOBALS['errorMsg']['noProceduerActionTypeParamsError']);
		}

		
		$this->proParams = $proParams;
		return $proParams;
	}
	
	/**
	 * 生成单条存储过程语句
	 * @param unknown $proName
	 * @param number $type
	 * @param string $count
	 */
	public function createProcedureSql($proName,$type=1)
	{
	    if($type==1){
	        $str='';
	
	    }else if($type==2){
	        $str=',@outId';
	    }else if( $type == 3 )
	    {
	        $str=',@inId';
	    }
	     
	    return "CALL {$this->nowActionDbName}.{$proName}({$this->proParams},@code,@msg{$str})";
	     
	}

    
	/**
	 * 拼接多存储过程语句
	 * @param unknown $array
	 * @return string
	 */
	public function jointProcedureSqls( $array )
	{
	    $str='start transaction;set @panding=1;';
	    $num=count($array)-1;
	    foreach( $array as $key => $val )
	    {   
	       if($key==$num)
           {
               $str .= $val."CALL EC_FUNCTION_PROCEDURE_CTRL(@code, '1');";
           }else{
               $str .= $val."CALL EC_FUNCTION_PROCEDURE_CTRL(@code, '0');";
           }   
	    }
	    
	    return $str;
	}
	
	/**
	 * 批量执行存储过程 
	 * @param unknown $sql
	 * @return number
	 */
	public function batchExecProcedure($sql)
	{
	    $res = $this->mysqlConn->multi_query($sql);
	    
	    $arr=[];
	    if ($res) {
	        do {
	            if ($result = $this->mysqlConn->store_result()) {
	                while ($row = $result->fetch_array()) {
	                    $arr[]= $row[0];
	                }
	               $result->free();
	            }
	             
	        } while (@$this->mysqlConn->next_result());
	    }
	    
	    $result = $arr[count($arr)-1];
	    if( $result == -90 )
	    {
	       return true;   
	    }
	    else
	    {
	        return false;
	    }
	}
	
	/*
	 * 执行存储过程
	 * @params {$proName} 存储过程名称
	 * @params {$params} 存储过程参数
	 * @params {$resultType} 返回的类型是带数据的类型还是不带数据的类型 ACTION - 不带数据 
	 * @return 返回最终拼接好的参数
	 */
	function execProceduer($proName,$params,$resultType="ACTION"){

		//结果保存数组
		$dataArr = array();

		//调用存储过程
		$proceStr = "CALL {$this->nowActionDbName}.{$proName}({$this->proParams},@code,@msg)";
		
		//获取存储过程结果
		$this->mysqlResult = $this->mysqlConn->query($proceStr,MYSQLI_STORE_RESULT);

		//查看存储过程是否调用成功
		if(!$this->mysqlResult){
			Error::Result("BUSINESS_ERROR",$GLOBALS['errorMsg']['noProceduerError']);
		}

		//获取存储过程返回CODE与MESSAGE
		$proCodeResult	= $this->mysqlConn->query("select @code");
		$proMsgResult   = $this->mysqlConn->query("select @msg");

		//获取CODE与MESSAGE信息
		$proCode = @mysqli_fetch_all($proCodeResult,MYSQLI_ASSOC)[0]['@code'];
		$proMsg  = @mysqli_fetch_all($proMsgResult, MYSQLI_ASSOC)[0]['@msg'];


		//判断存储过程返回类型
		if($resultType == "ACTION"){

			if($proCode < 0){
				Error::Result("BUSINESS_ERROR",$proMsg);	
			}

			return true;

		}else{
		
			//如果是数据返回类型，则获取返回数据信息
			@$proResult = mysqli_fetch_all($this->mysqlResult,MYSQLI_ASSOC)[0];

			if(!$proResult){
				Error::Result("BUSINESS_ERROR",$proMsg);
			}

			return $proResult;
		}

	}


	/*
	 * 释放存储过程占用的资源
	 * @return 没有返回值
	 */
	function clearStoredResults(){
	    while($this->mysqlConn->more_results() && $this->mysqlConn->next_result()){
	      if($l_result = $this->mysqlConn->store_result()){
	         $l_result->free();
	      }
	    }
	}

	/*
	 * 析构方法
	 * @return 没有返回值
	 */
	function __destruct(){

		//释放结果内存
		if($this->mysqlResult!=NULL){
			@mysqli_free_result($this->mysqlResult);
		}
		

		//关闭之前建立的mysql数据库连接
		if($this->mysqlConn!=NULL){
			@mysqli_close($this->mysqlConn);
		}
		

	}
	

}
